import {
  Body,
  Controller,
  Get,
  Patch,
  Post,
  Put,
  Query,
  Req,
} from '@nestjs/common';
import { UserService } from './user.service';
import { ResponseData, ResponseDataProps } from 'src/common/response.data';
import { UserLoginDto, UserUpdateDto, UserUpdatePwdDto } from './dto/user.dto';
import { AuthService } from 'src/shared/auth/auth.service';
import { instanceToPlain } from 'class-transformer';
import { MatchPasswordsPipe } from 'src/common/pipe';
import {
  ApiBearerAuth,
  ApiOperation,
  ApiResponse,
  ApiTags,
} from '@nestjs/swagger';
interface ReqUserProps {
  user: {
    userid: number;
    username: string;
  };
}

@ApiTags('用户模块')
@Controller('user')
export class UserController {
  constructor(
    private readonly userService: UserService,
    private authService: AuthService,
  ) {}
  @Post('register')
  async register(@Body() body: UserLoginDto): Promise<ResponseDataProps> {
    const user = await this.userService.findOneBy({
      username: body.username,
    });
    if (user) {
      return ResponseData.error('用户名已存在');
    }
    body.password = await this.authService.hashPassword(body.password);
    return ResponseData.success(await this.userService.createUser(body));
  }

  @ApiOperation({
    summary: '登录',
    description: '登录用的接口',
  })
  @ApiResponse({ type: ResponseDataProps })
  @Post('login')
  async login(@Body() body: UserLoginDto): Promise<ResponseDataProps> {
    const user = await this.userService.findOneBy({
      username: body.username,
    });

    if (!user) {
      return ResponseData.error('用户名不存在');
    }
    if (
      !(await this.authService.comparePassword(body.password, user.password))
    ) {
      return ResponseData.error('密码错误');
    }

    return ResponseData.success(this.authService.login(user));
  }

  @ApiBearerAuth()
  @Get('list')
  async getHello(): Promise<ResponseDataProps> {
    return ResponseData.success(await this.userService.findAll());
  }

  @ApiBearerAuth()
  @Get('userInfo')
  async getInfo(@Req() req: any): Promise<ResponseDataProps> {
    // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
    const user = await this.userService.findOneBy({ id: req?.user?.userid });
    return ResponseData.success(
      instanceToPlain({ ...user, userPic: user?.user_pic }),
    );
  }

  @ApiBearerAuth()
  @Put('update')
  async update(@Body() body: UserUpdateDto): Promise<ResponseDataProps> {
    return ResponseData.success(await this.userService.updateUser(body));
  }

  @ApiBearerAuth()
  @Patch('updateAvatar')
  async updateAvatar(
    @Req() req: ReqUserProps,
    @Body('avatarUrl') updateAvatarUrl: string,
  ): Promise<ResponseDataProps> {
    const data = await this.userService.updateAvater(
      req?.user.userid,
      updateAvatarUrl,
    );
    console.log('updateAvater controller ', updateAvatarUrl);
    return ResponseData.success(data);
  }

  /**
   *
   * 更新密码
   */
  @ApiBearerAuth()
  @Patch('updatePwd')
  async updatePwd(
    @Req() req: ReqUserProps,
    @Body(MatchPasswordsPipe) body: UserUpdatePwdDto,
  ): Promise<ResponseDataProps> {
    const user = await this.userService.findOneBy({
      username: req.user.username,
    });
    if (!user) {
      return ResponseData.error('用户名不存在');
    }
    if (
      !(await this.authService.comparePassword(body.old_pwd, user.password))
    ) {
      return ResponseData.error('密码错误');
    }
    body.id = req.user.userid;
    body.new_pwd = await this.authService.hashPassword(body.new_pwd);
    const data = await this.userService.updatePwd(body);
    return ResponseData.success(data);
  }
}
